package cn.edu.ccut.refactor;

import org.eclipse.jface.util.Assert;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;

/**
 * 
 * @author Bai Yucheng 2008-1-8
 * 
 */
public abstract class TextInputWizardPage extends UserInputWizardPage {
	private String fInitialValue;
	private Text fTextField;
	public static final String PAGE_NAME = "TextInputPage"; 

	public TextInputWizardPage(String s, boolean flag) {
		this(s, flag, ""); 
	}

	public TextInputWizardPage(String s, boolean flag, String s1) {
		super("TextInputPage"); 
		Assert.isNotNull(s1);
		setDescription(s);
		fInitialValue = s1;
	}

	protected boolean isInitialInputValid() {
		return false;
	}

	protected boolean isEmptyInputValid() {
		return false;
	}

	protected String getText() {
		if (fTextField == null)
			return null;
		else
			return fTextField.getText();
	}

	protected void setText(String s) {
		if (fTextField == null) {
			return;
		} else {
			fTextField.setText(s);
			return;
		}
	}

	protected RefactoringStatus validateTextField(String s) {
		return null;
	}

	protected Text createTextInputField(Composite composite) {
		return createTextInputField(composite, 2048);
	}

	protected Text createTextInputField(Composite composite, int i) {
		fTextField = new Text(composite, i);
		fTextField.addModifyListener(new ModifyListener() {

			public void modifyText(ModifyEvent modifyevent) {
				textModified(getText());
			}

		});
		fTextField.setText(fInitialValue);
		return fTextField;
	}

	protected void textModified(String s) {
		if (!isEmptyInputValid() && s.equals("")) { 
			setPageComplete(false);
			setErrorMessage(null);
			restoreMessage();
			return;
		}
		if (!isInitialInputValid() && s.equals(fInitialValue)) {
			setPageComplete(false);
			setErrorMessage(null);
			restoreMessage();
			return;
		} else {
			setPageComplete(validateTextField(s));
			return;
		}
	}

	protected void restoreMessage() {
		setMessage(null);
	}

	public void dispose() {
		fTextField = null;
	}

	public void setVisible(boolean flag) {
		if (flag)
			textModified(getText());
		super.setVisible(flag);
		if (flag && fTextField != null)
			fTextField.setFocus();
	}

}
